package com.example.test02;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.documentfile.provider.DocumentFile;
import androidx.fragment.app.Fragment;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.FileOutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class GuardFragment extends Fragment {

    private static final int REQUEST_SELECT_MEDIA = 1;
    private ImageView uploadImageView;
    private ActivityResultLauncher<Intent> mediaPickerLauncher;
    private static final int REQUEST_LOGIN = 2; // 你可以使用任何未被使用的请求码
    private ActivityResultLauncher<Intent> loginLauncher;

    private void startLoginActivity() {
        Intent intent = new Intent(requireContext(), LoginActivity.class);
        loginLauncher.launch(intent);
    }



    private final ActivityResultLauncher<String[]> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
                boolean allPermissionsGranted = true;
                if (!result.getOrDefault(Manifest.permission.READ_MEDIA_IMAGES, false)) {
                    allPermissionsGranted = false;
                }
                if (!result.getOrDefault(Manifest.permission.READ_MEDIA_VIDEO, false)) {
                    allPermissionsGranted = false;
                }
                if (!result.getOrDefault(Manifest.permission.READ_MEDIA_AUDIO, false)) {
                    allPermissionsGranted = false;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !result.getOrDefault(Manifest.permission.ACCESS_MEDIA_LOCATION, false)) {
                    allPermissionsGranted = false;
                }
                if (allPermissionsGranted) {
                    // 所有权限都已被授予，启动媒体选择器
                    launchMediaPicker();
                } else {
                    // 权限被拒绝，显示提示对话框
                    showPermissionDeniedDialog();
                }
            });




    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        // 初始化登录的 ActivityResultLauncher
        loginLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // 用户登录成功，可以在这里进行一些后续操作
                        int userId = getUserIdFromCache();
                        if (userId != -1) {
                            // 用户已登录，可以继续之前的操作
                            Toast.makeText(requireActivity(), "用户已登录", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

        // 初始化媒体选择器
        mediaPickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Uri uri = result.getData() != null ? result.getData().getData() : null;
                        if (uri != null) handleSelectedMediaUri(uri);
                    }
                });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_guard, container, false);

        TextView userNameTextView = view.findViewById(R.id.guard_name);
        String userName = getUserNameFromCache();
        if (userNameTextView != null) {
            userNameTextView.setText(userName);
        }

        uploadImageView = view.findViewById(R.id.upload_image);
        LinearLayout uploadMediaButton = view.findViewById(R.id.upload);
        uploadMediaButton.setOnClickListener(v -> checkAndRequestPermissions());

        // 请求消息接口
        requestMessages();

        // 检测用户登录状态
        if (getUserIdFromCache() == -1) {
            startLoginActivity();
        }

        Log.d("GuardFragment", "onCreateView called");
        return view;
    }


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mediaPickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == AppCompatActivity.RESULT_OK && result.getData() != null) {
                        Uri selectedMediaUri = result.getData().getData();
                        if (selectedMediaUri != null) {
                            handleSelectedMediaUri(selectedMediaUri);
                        }
                    }
                }
        );
    }

    private void launchMediaPicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); // 替换 ACTION_GET_CONTENT
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{"image/*", "video/*", "audio/*"});
        mediaPickerLauncher.launch(intent);
    }

    private void handleSelectedMediaUri(Uri selectedMediaUri) {
        if (selectedMediaUri.toString().contains("video")) {
            Bitmap videoThumbnail = getVideoThumbnail(selectedMediaUri);
            if (videoThumbnail != null) {
                uploadImageView.setImageBitmap(videoThumbnail);
            } else {
                Toast.makeText(requireActivity(), "无法获取视频封面", Toast.LENGTH_SHORT).show();
            }
        } else if (selectedMediaUri.toString().contains("audio")) {
            // 音频文件处理逻辑
            uploadImageView.setImageResource(R.drawable.ic_audio_placeholder);
        } else {
            uploadImageView.setImageURI(selectedMediaUri);
        }
        uploadMedia(selectedMediaUri);
    }

    private Bitmap getVideoThumbnail(Uri videoUri) {
        Bitmap bitmap = null;
        try {
            bitmap = ThumbnailUtils.createVideoThumbnail(getPathFromUri(videoUri), MediaStore.Video.Thumbnails.MINI_KIND);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }



    private void uploadMedia(Uri mediaUri) {
        int userId = getUserIdFromCache();
        if (userId == -1) {
            Toast.makeText(requireActivity(), "用户未登录或 userId 未缓存", Toast.LENGTH_SHORT).show();
            return;
        }

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(180, TimeUnit.SECONDS)
                .writeTimeout(180, TimeUnit.SECONDS)
                .readTimeout(180, TimeUnit.SECONDS)
                .build();

        String fileName = getFileName(mediaUri);

        // 获取文件的 MIME 类型
        MediaType mediaType = getMediaTypeFromUri(requireActivity(), mediaUri);

        try {
            // 使用 ContentResolver 直接读取文件流
            InputStream inputStream = requireContext().getContentResolver().openInputStream(mediaUri);
            if (inputStream == null) {
                Toast.makeText(requireActivity(), "无法读取文件流", Toast.LENGTH_SHORT).show();
                return;
            }

            // 读取文件内容到字节数组
            byte[] fileBytes = readBytes(inputStream);

            // 构建请求体
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("mediaFile", fileName, RequestBody.create(fileBytes, mediaType))
                    .build();

            String uploadUrl = "http://120.26.59.7:17321/api/video/upload?userId=" + userId;
            Request request = new Request.Builder()
                    .url(uploadUrl)
                    .post(requestBody)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireActivity(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireActivity(), "服务器返回错误: " + response.code(), Toast.LENGTH_SHORT).show();
                        });
                        return;
                    }

                    String responseData = response.body().string();
                    System.out.println("Response Data: " + responseData);
                    try {
                        JSONObject jsonResponse = new JSONObject(responseData);
                        int code = jsonResponse.getInt("code");
                        JSONObject data = jsonResponse.getJSONObject("data");
                        String message = data.getString("messageContent");

                        requireActivity().runOnUiThread(() -> {
                            if (code == 0) {
                                Toast.makeText(requireActivity(), "上传成功: " + message, Toast.LENGTH_SHORT).show();
                                createAndSendNotification(message); // 调用通知创建方法
                                // 保存 URI 并获取持久化权限
                                SharedPreferences prefs = requireActivity().getSharedPreferences("media_prefs", Context.MODE_PRIVATE);
                                prefs.edit().putString("last_media_uri", mediaUri.toString()).apply();

                                // 确保 URI 权限持久化（关键！）
                                requireActivity().getContentResolver().takePersistableUriPermission(
                                        mediaUri,
                                        Intent.FLAG_GRANT_READ_URI_PERMISSION
                                );
                            } else {
                                Toast.makeText(requireActivity(), "上传失败: " + message, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (Exception e) {
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireActivity(), "解析响应数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            });
        } catch (Exception e) {
            requireActivity().runOnUiThread(() -> {
                Toast.makeText(requireActivity(), "文件读取失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            });
        }
    }

    // 辅助方法，用于获取文件的 MIME 类型
    private MediaType getMediaTypeFromUri(Context context, Uri uri) {
        String mimeType = context.getContentResolver().getType(uri);
        System.out.println("MIME type of the file is: " + mimeType);
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
        return MediaType.parse(mimeType);
    }
    //通知渠道
    private String createNotificationChannel(String channelId, String channelName, int importance) {
        // 检查是否是 Android O 及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 创建通知渠道
            NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
            channel.setDescription("通知渠道描述"); // 可以设置渠道描述
            NotificationManager notificationManager = requireContext().getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
        return channelId; // 返回渠道 ID
    }

    //创建通知
    private void createAndSendNotification(String message) {
        // 1. 检查通知权限（Android 13+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                // 单独请求通知权限
                ActivityCompat.requestPermissions(
                        requireActivity(),
                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                        1001 // 自定义请求码
                );
                return; // 权限未授予时直接返回
            }
        }

        // 2. 创建通知渠道
        String channelId = createNotificationChannel("my_channel_ID", "上传通知", NotificationManager.IMPORTANCE_HIGH);

        // 3. 构建通知（使用有效的小图标）
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(requireContext(), channelId)
                .setContentTitle("上传成功")
                .setContentText(message)
                .setSmallIcon(R.drawable.notice_yellow) // 确保此图标存在
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true);

        // 4. 发送通知
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(requireContext());
        try {
            notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build()); // 使用唯一ID
        } catch (SecurityException e) {
            Log.e("Notification", "权限不足: " + e.getMessage());
        }
    }



    private byte[] readBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

    private String getFileName(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            Cursor cursor = requireActivity().getContentResolver().query(uri, new String[]{"_display_name"}, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    result = cursor.getString(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
        if (result == null) {
            result = "media";
        }
        return result;
    }

    private int getUserIdFromCache() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        return sharedPreferences.getInt("userId", -1);
    }

    private String getPathFromUri(Uri uri) {
        if (uri == null) return null;

        // 处理 content:// 协议的 URI（如相册文件）
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            try (InputStream inputStream = requireContext().getContentResolver().openInputStream(uri)) {
                // 创建临时文件
                File tempFile = File.createTempFile("upload_", ".tmp", requireContext().getCacheDir());
                try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                    byte[] buffer = new byte[4 * 1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    return tempFile.getAbsolutePath();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 处理 file:// 协议的 URI（直接路径）
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    private String getUserNameFromCache() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        return sharedPreferences.getString("userName", "");
    }

    private void openAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", requireActivity().getPackageName(), null);
        intent.setData(uri);
        requireActivity().startActivity(intent);
    }

    //权限检测
    private void checkAndRequestPermissions() {
        // 1. 检查媒体权限
        if (checkMediaPermissions()) {
            // 媒体权限已授予，检查通知权限
            checkNotificationPermission();
        } else {
            // 请求媒体权限
            requestMediaPermissions();
        }
    }

    // 检查媒体权限是否全部授予
    private boolean checkMediaPermissions() {
        boolean isGranted = true;
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
            isGranted = false;
        }
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) {
            isGranted = false;
        }
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            isGranted = false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
                ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_MEDIA_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            isGranted = false;
        }
        return isGranted;
    }

    // 单独请求媒体权限
    private void requestMediaPermissions() {
        List<String> permissionsNeeded = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
            permissionsNeeded.add(Manifest.permission.READ_MEDIA_IMAGES);
        }
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) {
            permissionsNeeded.add(Manifest.permission.READ_MEDIA_VIDEO);
        }
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            permissionsNeeded.add(Manifest.permission.READ_MEDIA_AUDIO);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
                ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_MEDIA_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionsNeeded.add(Manifest.permission.ACCESS_MEDIA_LOCATION);
        }

        if (!permissionsNeeded.isEmpty()) {
            requestPermissionLauncher.launch(permissionsNeeded.toArray(new String[0]));
        }
    }

    // 单独处理通知权限
    private void checkNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                // 显示解释对话框（可选）
                new AlertDialog.Builder(requireContext())
                        .setTitle("需要通知权限")
                        .setMessage("请允许通知权限以接收上传状态")
                        .setPositiveButton("去设置", (dialog, which) ->
                                ActivityCompat.requestPermissions(
                                        requireActivity(),
                                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                                        1001
                                ))
                        .setNegativeButton("取消", null)
                        .show();
            } else {
                launchMediaPicker();
            }
        } else {
            launchMediaPicker();
        }
    }



    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("需要权限")
                .setMessage("需要媒体访问权限来上传文件")
                .setPositiveButton("设置", (d, w) -> openAppSettings())
                .setNegativeButton("取消", null)
                .show();
    }

    // 获取最新消息
    private void requestMessages() {
        int userId = getUserIdFromCache();
        if (userId == -1) {
            Toast.makeText(requireActivity(), "用户未登录或 userId 未缓存", Toast.LENGTH_SHORT).show();
            return;
        }

        OkHttpClient client = new OkHttpClient();
        String url = "http://120.26.59.7:17321/api/messages?userId=" + userId;
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireActivity(), "服务器返回错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                String responseData = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseData);
                    int code = jsonResponse.getInt("code");
                    if (code == 0) {
                        JSONArray data = jsonResponse.getJSONArray("data");
                        if (data.length() > 0) {
                            JSONObject newestMessage = data.getJSONObject(0); // 提取第一条消息
                            renderNewestMessage(newestMessage); // 渲染第一条消息
                        } else {
                            requireActivity().runOnUiThread(() -> {
                                Toast.makeText(requireActivity(), "没有消息数据", Toast.LENGTH_SHORT).show();
                            });
                        }
                    } else {
                        requireActivity().runOnUiThread(() -> {
                            try {
                                Toast.makeText(requireActivity(), "服务器返回错误: " + jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        });
                    }
                } catch (Exception e) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireActivity(), "解析响应数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }
    // 组件渲染
    private void renderNewestMessage(JSONObject message) {
        requireActivity().runOnUiThread(() -> {
            TextView descriptionTextView = requireActivity().findViewById(R.id.item_description);
            TextView dateTextView = requireActivity().findViewById(R.id.item_date);
            TextView timeTextView = requireActivity().findViewById(R.id.item_time);
            ImageView iconImageView = requireActivity().findViewById(R.id.item_icon);

            // 设置消息内容
            String messageContent = message.optString("messageContent", "无内容");
            descriptionTextView.setText(messageContent);

            // 设置日期和时间
            String sendDate = message.optString("sendDate", "");
            if (sendDate.contains(" ")) {
                String[] parts = sendDate.split(" ");
                if (parts.length > 1) {
                    dateTextView.setText(parts[0]);
                    timeTextView.setText(parts[1].substring(0, 5));
                } else {
                    dateTextView.setText("未知日期");
                    timeTextView.setText("未知时间");
                }
            } else {
                dateTextView.setText("未知日期");
                timeTextView.setText("未知时间");
            }

            // 设置图标
            if (messageContent.contains("未")) {
                iconImageView.setImageResource(R.drawable.not_fake_safe);
            } else {
                iconImageView.setImageResource(R.drawable.warnning);
            }

            // 为消息组件设置点击事件
            View messageContainer = requireActivity().findViewById(R.id.newest_message);
            messageContainer.setOnClickListener(v -> {
                // 获取保存的媒体文件 URI
                SharedPreferences prefs = requireActivity().getSharedPreferences("media_prefs", Context.MODE_PRIVATE);
                String mediaUriString = prefs.getString("last_media_uri", null);

                if (mediaUriString != null) {
                    // 跳转到结果页面
                    Intent intent = new Intent(requireActivity(), ResultActivity.class);
                    intent.putExtra("message_content", messageContent);
                    intent.putExtra("send_date",sendDate);
                    intent.putExtra("media_uri", mediaUriString);
                    startActivity(intent);
                } else {
                    Toast.makeText(requireActivity(), "未找到媒体文件", Toast.LENGTH_SHORT).show();
                }
            });
        });
    }






}



